#include <QtOpenGL>

#include "glwidget.hpp"
#include <iostream>
#include "ShadowMapping/shaderExample.hpp"

float xRot = 0.0, yRot = 0.0;

GLWidget::GLWidget(QWidget *parent) :
    QGLWidget(parent)
{
    setFocusPolicy(Qt::StrongFocus);
    glslTest = ShaderExample();

	connect(&timer, SIGNAL(timeout()), this, SLOT(updateGL()));
    timer.start(0);
	frame_count = 0;
	last_count = 0;
	last_time = QTime::currentTime();
}

GLWidget::~GLWidget()
{
}

void GLWidget::initializeGL()
{
    glslTest.init();
}

void GLWidget::resizeGL(int width, int height)
{
    glslTest.resize(width, height);
}

void GLWidget::paintGL()
{

    glslTest.draw();

	++frame_count;
	QTime new_time = QTime::currentTime();
	// if 1 sec (1000 msec) ellapsed
	if (last_time.msecsTo(new_time) >= 1000)
	{
		last_count = frame_count;
		frame_count = 0;
		last_time = QTime::currentTime();
	}

        glColor3f(1.0, 1.0, 1.0);
        renderText(10, 20, QString::number(last_count));
}

void GLWidget::mousePressEvent(QMouseEvent *event)
{
    lastPos = event->pos();
}

void GLWidget::mouseMoveEvent(QMouseEvent *event)
{
    int dx = event->x() - lastPos.x();
    int dy = event->y() - lastPos.y();

    if (event->buttons() & Qt::LeftButton) {
        glslTest.turnView(dx*0.1, dy*0.1);
    } else if (event->buttons() & Qt::RightButton) {
        ;
    }
    lastPos = event->pos();
	updateGL();
}

void GLWidget::keyPressEvent(QKeyEvent *event){
    switch(event->key())
    {
        case Qt::Key_Z:
        {
            glslTest.translateView(0.1,0.0,0.0);
            break;
        }
        case Qt::Key_S:
        {
            glslTest.translateView(-0.1,0.0,0.0);
            break;
        }
        case Qt::Key_Q:
        {
            glslTest.translateView(0.0,0.1,0.0);
            break;
        }
        case Qt::Key_D:
        {
            glslTest.translateView(0.0,-0.1,0.0);
            break;
        }
        case Qt::Key_Space:
        {
            glslTest.translateView(0.0,0.0,0.1);
            break;
        }
        case Qt::Key_Alt:
        {
            glslTest.translateView(0.0,0.0,-0.1);
            break;
        }
        case Qt::Key_Return:
        {
            glslTest.animateLight();
            break;
        }
    }
	updateGL();
}
